import os
import shutil
from PIL import Image


def split_images_by_resolution(source_dir, target_root):
    """
    根据分辨率的不同将不相同图片划分到相同的分辨率文件夹中去
    将指定目录下的图片按分辨率分类复制到不同子目录中。
    子目录命名格式为 '宽_高'。
    """
    os.makedirs(target_root, exist_ok=True)

    for filename in os.listdir(source_dir):
        file_path = os.path.join(source_dir, filename)

        if not os.path.isfile(file_path):
            continue

        try:
            with Image.open(file_path) as img:
                width, height = img.size
                res_folder_name = f"{width}_{height}"
                target_dir = os.path.join(target_root, res_folder_name)
                os.makedirs(target_dir, exist_ok=True)
                shutil.copy(file_path, os.path.join(target_dir, filename))
        except Exception as e:
            print(f"处理文件 {filename} 时发生错误: {e}")


if __name__ == "__main__":
    source_folder = r"F:\yolo_summary\yolo_code\car\521\test"
    output_folder = r"F:\yolo_summary\yolo_code\car\521\test_split"

    split_images_by_resolution(source_folder, output_folder)
